package com.xyd.Servlet;

import com.xyd.Biz.CommodityBiz;
import com.xyd.Biz.Impl.CommodityBizImpl;
import com.xyd.Entity.Commodity;
import com.xyd.Entity.Page;
import com.xyd.Util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/html/manage/ProductServlet")
public class ProductServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageNum = request.getParameter("pageNum");
        if (pageNum == null) {
            pageNum = "1";
        }
        int pageId = Integer.parseInt(pageNum);
        CommodityBiz commodityBiz = new CommodityBizImpl();
        int count = commodityBiz.getCommodityCount();
        int totalPages = PageUtil.getTotalPages(count, PageUtil.PAGE_SIZE);


        if (pageId < 1) {
            pageId = 1;
        }
        if (pageId > totalPages) {
            pageId = totalPages;
        }
        int pageIndex = PageUtil.PAGE_SIZE * (pageId - 1);
        System.out.println(pageId);

        Page page = new Page();
        page.setPageIndex(pageIndex);
        page.setPageSize(PageUtil.PAGE_SIZE);

        List<Commodity> commodityList = commodityBiz.getAllCommodityByPage(page);

        request.setAttribute("pageId",pageId);
        request.setAttribute("commodityList", commodityList);

        request.getRequestDispatcher("product.jsp").forward(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
